"""
    接收请求，逻辑处理，发送响应
"""
from socket import *
from multiprocessing import Process
from threading import Thread
import sys
from dict_db import *

# 进程类做事情
class Handle(Process):
    def __init__(self,conn,addr):
        self.conn=conn
        self.addr=addr
        self.name="" #记录登录状态
        self.db=DICT()   # 得到数据库处理对象
        super().__init__()
    # 循环接收请求，分情况讨论
    def run(self):
        while True:
            request = self.conn.recv(1024)
            tmp=request.decode().split("\t")
            if not request or tmp[0] =="E":
                break  # 客户端退出
            elif tmp[0] == "R":
                self.do_register(tmp[1],tmp[2])
            elif tmp[0] == "L":
                self.do_login(tmp[1],tmp[2])
            elif tmp[0] == "Q":
                self.do_query(tmp[1])
            elif tmp[0] == "H":
                self.do_hist()

        self.db.close()
        self.conn.close()

    def do_register(self, name,password):
        # 数据库的操作
        if self.db.register(name,password):
            self.conn.send(b"T")
        else:
            self.conn.send(b"F")

    def do_login(self, name, password):
        if self.db.login(name,password):
            self.conn.send(b"T")
            self.name=name #改变name实例变量记录登录状态
        else:
            self.conn.send(b"F")

    def do_query(self, word):
        # (mean,) None
        mean=self.db.query(word)
        if mean:
            res="T\t"+mean[0]
            self.conn.send(res.encode())
            self.db.insert_hist(self.name,word) #历史记录
        else:
            self.conn.send(b"F")
    def do_hist(self):
        # ((name:,word,time)...)
        data=self.db.hist(self.name)
        if data:
            res="T\t"
            for row in data:
                res += "%s,%s,%s;" % row
            self.conn.send(res.encode())
        else:
            self.conn.send(b"F")
# 网络服务
class DICTServer:
    def __init__(self, host="",port=0):
        self.host=host
        self.port=port
        self.address=(self.host,self.port)
        self.sock=self._create_socket()

    def _create_socket(self):
        sock=socket(AF_INET,SOCK_STREAM)
        sock.bind(self.address)
        return sock
    # 启动服务
    def server_forver(self):
        self.sock.listen(5)
        print("Listen the port %d" % self.port)
        # 循环连接客户端
        while True:
            conn, addr = self.sock.accept()
            print("Connect from", addr)
            handle=Handle(conn,addr)
            handle.run()  # 将此处改为了run，若仍为start并不能运行，会报错TypeError: cannot pickle '_io.BufferedReader' object

if __name__ == '__main__':
    server=DICTServer(host="0.0.0.0",port=8888)
    server.server_forver()  #启动服务
